package com.itboye.ihomebank.home;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.adapter.HeTongAdapter;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.HeTongBean;
import com.itboye.ihomebank.bean.HetongCaoGao;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.db.HeTongDBManager;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.support.commonadapter.MutiplyCommonAdapter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.DoubleDatePickerDialog;
import com.itboye.ihomebank.util.SPUtils;

public class ActivityEditHeTongFangdong extends BaseOtherActivity implements
		Observer {

	TextView add_shap_title_tv;
	ImageView close_icon;
	private String contractNo;
	private String uid;
	private UserPresenter userPresenter;
	private ArrayList<TextView> devices = new ArrayList<>();
	private Calendar current = Calendar.getInstance(Locale.CHINA);
	private ArrayList<EditText> editTexts = new ArrayList<>();
	private LinearLayout li_container;
	private ArrayList<View> views = new ArrayList<View>();
	protected String yajin;
	protected int selectEndYear;
	protected int selectStartYear;
	protected int qishu;
	private int selectStartMonth;
	private int selectEndMonth;
	HeTongDBManager heTongDBManager;
	private HetongCaoGao caoGao;
	private String selectDevice;
	private String selectFeiYong;
	private String unselectFeiYong;
	private String zujinxinxi;
	private String imgId;
	Button tijiao;
	private HeTongDBManager dbManager;
	protected String tempStartTimes;
	protected String tempEndTimes;

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.close_icon:
			finish();
			break;
		case R.id.tijiao:
			long re = heTongDBManager.deleteCaoGao(uid, contractNo);
			if (re > 0) {
//				ByAlert.alert("删除成功");
			} else {
//				ByAlert.alert("删除失败");
			}
			buildJson();// 生成json数据
			break;
		default:
			break;
		}
	}

	private void buildJson() {
		// TODO Auto-generated method stub
		HeTongDBManager deleteCaoGao = new HeTongDBManager(this);
		HashMap<String, String> map = new HashMap<String, String>();
		deleteCaoGao.deleteCaoGao(uid, contractNo);
		for (int i = 0; i < views.size(); i++) {
			EditText editText = (EditText) views.get(i).findViewById(R.id.edit);
			if (views.get(i).getTag().equals("rent_info")) {// 房租信息
				map.put(editText.getTag() + "", zujinxinxi);
			} else if (views.get(i).getTag().equals("lessor_fee_items")
					|| views.get(i).getTag().equals("renter_fee_items")
					|| views.get(i).getTag().equals("facility")) {
				TextView textView = (TextView) views.get(i).findViewById(
						R.id.txt_device);
				map.put(editText.getTag() + "", textView.getText().toString());
			} else {
				map.put(editTexts.get(i).getTag() + "", editTexts.get(i)
						.getText().toString());
			}
		}
		Gson gson = new Gson();
		String jsonStr = gson.toJson(map);
		heTongDBManager = new HeTongDBManager(this);
		long re = heTongDBManager.addNote(uid, contractNo, jsonStr);
		if (re > 0) {
//			ByAlert.alert("添加成功" + contractNo);
		} else {
//			ByAlert.alert("添加失败");
		}
		 userPresenter.tiJiaoHeTong(uid, contractNo, jsonStr);
		System.out.println("》》生成的json字符串" + jsonStr);
	}

	@Override
	protected int layout_id() {
		// TODO Auto-generated method stub
		return R.layout.activity_hetong;
	}

	@Override
	protected void onInitController() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onInit() {
		// TODO Auto-generated method stub
		add_shap_title_tv.setText("修改合同房东");
		uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
		contractNo = getIntent().getStringExtra("contractNo");
		tijiao.setVisibility(View.GONE);
		heTongDBManager = new HeTongDBManager(this);
		String str = heTongDBManager.getCaoGaoStr(uid, contractNo);
		if (!str.equals("")) {
			Gson gson = new Gson();
			caoGao = gson.fromJson(str, HetongCaoGao.class);
			if (caoGao != null) {
				selectDevice = caoGao.getFacility();
				selectFeiYong = caoGao.getLessor_fee_items();
				unselectFeiYong = caoGao.getRenter_fee_items();
				zujinxinxi = caoGao.getRent_info();
				imgId = caoGao.getSign_leaser();
			}
			userPresenter = new UserPresenter(this);
			userPresenter.heTongParams("0");
		} else {
			ByAlert.alert("未查询到草稿信息");
		}

	}

	@Override
	protected void onReadIntent(Bundle bundle) {
		// TODO Auto-generated method stub

	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			Gson gson = new Gson();
			if (entity.getEventType() == UserPresenter.heTongParams_success) {
				@SuppressWarnings("unchecked")
				List<HeTongBean> datas = (List<HeTongBean>) entity.getData();
				HeTongAdapter adapter = new HeTongAdapter(this, datas,
						R.layout.item_hetong);
				Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
				for (int i = 0; i < datas.size(); i++) {
					// map2.put(datas.get(i).getAlias(), )
					HeTongBean bean = datas.get(i);
					Integer inputType = bean.getValueType();// 5、整型 1、字符串 4、日期
															// 0、点击进去 2、签字

					final View view = LayoutInflater.from(this).inflate(
							R.layout.item_hetong, null);
					TextView txt_device = (TextView) view
							.findViewById(R.id.txt_device);
					devices.add(txt_device);
					TextView text = (TextView) view.findViewById(R.id.txt);
					EditText editText = (EditText) view.findViewById(R.id.edit);
					switch (inputType) {// 1: 文本、2: 图片、3: 当前时间 4：当前日期 5：数字 ,默认0
					case 1:
						editText.setInputType(InputType.TYPE_CLASS_TEXT);
						break;
					case 2:

						break;
					case 3:

						break;
					case 4:

						break;
					case 5:
						editText.setInputType(InputType.TYPE_CLASS_NUMBER);
						break;

					default:
						break;
					}
					editText.setTag(bean.getKey());
					editText.setHint(bean.getDesc());
					if (bean.getKey().equals("start_date")) {// 1
						editText.setEnabled(false);
						editText.setText(caoGao.getStart_date());
					}
					if (bean.getKey().equals("end_date")) {// 2
						editText.setEnabled(false);
						editText.setText(caoGao.getEnd_date() == null ? ""
								: caoGao.getEnd_date());
					}
					if (bean.getKey().equals("rent_info")) {// 3
						editText.setEnabled(false);
						editText.setText(caoGao.getRent_info() == null ? ""
								: "已填写");
					}
					if (bean.getKey().equals("sign_leaser")) {// 4
						editText.setEnabled(false);
						editText.setText(caoGao.getSign_leaser() == null ? ""
								: "已签名");
					}
					if (bean.getKey().equals("sign_leaser_year")) {// 6
						editText.setText(current.get(Calendar.YEAR) + "年");
						editText.setEnabled(false);
					}
					if (bean.getKey().equals("sign_leaser_month")) {// 7
						editText.setText((current.get(Calendar.MONTH) + 1)
								+ "月");
						editText.setEnabled(false);
					}
					if (bean.getKey().equals("sign_leaser_day")) {// 8
						editText.setText(current.get(Calendar.DATE) + "日");
						editText.setEnabled(false);
					}
					if (bean.getKey().equals("lesser")) {// 9
						editText.setText(caoGao.getLesser() == null ? ""
								: caoGao.getLesser());
					}
					if (bean.getKey().equals("renter")) {// 10
						editText.setText(caoGao.getRenter() == null ? ""
								: caoGao.getRenter());
					}
					if (bean.getKey().equals("address")) {// 11
						editText.setText(caoGao.getAddress() == null ? ""
								: caoGao.getAddress());
					}
					if (bean.getKey().equals("area")) {// 12
						editText.setText(caoGao.getArea() == null ? "" : caoGao
								.getArea());
					}
					if (bean.getKey().equals("id_renter")) {// 13
						editText.setText(caoGao.getId_renter() == null ? ""
								: caoGao.getId_renter());
					}
					if (bean.getKey().equals("id_leaser")) {// 14
						editText.setText(caoGao.getId_leaser() == null ? ""
								: caoGao.getId_leaser());
					}
					if (bean.getKey().equals("house_property")) {// 15
						editText.setText(caoGao.getHouse_property() == null ? ""
								: caoGao.getHouse_property());
					}
					if (bean.getKey().equals("rent_use")) {// 16
						editText.setText(caoGao.getRent_use() == null ? ""
								: caoGao.getRent_use());
					}
					if (bean.getKey().equals("max_people")) {// 17
						editText.setText(caoGao.getMax_people() == null ? ""
								: caoGao.getMax_people());
					}
					if (bean.getKey().equals("people_number")) {// 18
						editText.setText(caoGao.getPeople_number() == null ? ""
								: caoGao.getPeople_number());
					}
					if (bean.getKey().equals("deposit")) {// 19
						editText.setText(caoGao.getDeposit() == null ? ""
								: caoGao.getDeposit());

					}
					if (bean.getKey().equals("pay_type")) {// 20
						editText.setText(caoGao.getPay_type() == null ? ""
								: caoGao.getPay_type());
					}
					if (bean.getKey().equals("water_meter_reading")) {// 21
						editText.setText(caoGao.getWater_meter_reading() == null ? ""
								: caoGao.getWater_meter_reading());
					}
					if (bean.getKey().equals("gas_reading")) {// 22
						editText.setText(caoGao.getGas_reading() == null ? ""
								: caoGao.getGas_reading());
					}
					if (bean.getKey().equals("electric_instrument_reading")) {// 23
						editText.setText(caoGao
								.getElectric_instrument_reading() == null ? ""
								: caoGao.getElectric_instrument_reading());
					}
					if (bean.getKey().equals("repair_period")) {// 24
						editText.setText(caoGao.getRepair_period() == null ? ""
								: caoGao.getRepair_period());
					}
					if (bean.getKey().equals("arrears_months")) {// 25
						editText.setText(caoGao.getArrearsMonths() == null ? ""
								: caoGao.getArrearsMonths());
					}
					if (bean.getKey().equals("lessor_fee_items")) {// 26
						txt_device.setVisibility(View.VISIBLE);
						editText.setEnabled(false);
						txt_device
								.setText(caoGao.getLessor_fee_items() == null ? ""
										: caoGao.getLessor_fee_items());
					}
					if (bean.getKey().equals("renter_fee_items")) {// 27
						txt_device.setVisibility(View.VISIBLE);
						editText.setEnabled(false);
						txt_device
								.setText(caoGao.getRenter_fee_items() == null ? ""
										: caoGao.getRenter_fee_items());
					}
					if (bean.getKey().equals("facility")) {// 28
						editText.setEnabled(false);
						editText.setText(caoGao.getFacility() == null ? ""
								: caoGao.getFacility());
					}if (bean.getKey().equals("phone_leaser")) {// 28
						editText.setEnabled(true);
						editText.setText(caoGao.getPhone_leaser() == null ? ""
								: caoGao.getPhone_leaser());
					}

					editTexts.add(editText);// 将所有的编辑框放进集合

					text.setText(bean.getAlias());
					li_container
							.addView(view, li_container.getChildCount() - 1);
					view.setTag(datas.get(i).getKey() + "");
					views.add(view);
					view.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if ((v.getTag() + "").equals("facility")) {
								Intent intent = new Intent(
										ActivityEditHeTongFangdong.this,
										ActivityTianXieHeTongThree.class);
								startActivityForResult(intent, 101);
							}
							if ((v.getTag() + "").equals("lessor_fee_items")
									|| (v.getTag() + "")
											.equals("renter_fee_items")) {
								Intent intent = new Intent(
										ActivityEditHeTongFangdong.this,
										ActivityFeiYongFenTan.class);
								startActivityForResult(intent, 103);
							}
							if ((v.getTag() + "").equals("sign_leaser")) {// 甲方签字
								Intent intent = new Intent(
										ActivityEditHeTongFangdong.this,
										ActivityHuaBan.class);
								startActivityForResult(intent, 107);//
							}
							if ((v.getTag() + "").equals("rent_info")) {
								//
								for (View editText : views) {
									if (editText.getTag().toString()
											.equals("deposit")) {
										if (((EditText) editText
												.findViewById(R.id.edit))
												.getText().toString()
												.equals("")) {
											ByAlert.alert("请先输入预付押金");
											return;
										}
										yajin = ((EditText) editText
												.findViewById(R.id.edit))
												.getText().toString();
									}
									if ((editText.getTag() + "")
											.equals("start_date")
											|| (editText.getTag() + "")
													.equals("end_date")) {
										if (((EditText) editText
												.findViewById(R.id.edit))
												.getText().toString()
												.equals("")) {
											ByAlert.alert("请选择起租或止租年月");
											return;
										} else {
											if ((editText.getTag() + "")
													.equals("start_date")) {
												tempStartTimes = ((EditText) editText
														.findViewById(R.id.edit))
														.getText().toString();
											} else {
												tempEndTimes = ((EditText) editText
														.findViewById(R.id.edit))
														.getText().toString();
											}
										}
									}
								}
								String[] startYears = tempStartTimes.split("-");
								String[] endYears = tempEndTimes.split("-");
								if ((Integer.parseInt(startYears[0])
										- (Integer.parseInt(endYears[0])) > 0)) {
									ByAlert.alert("起租年应小于止租年");
									return;
								}
								if ((Integer.parseInt(startYears[1])
										- (Integer.parseInt(endYears[1])) > 0)) {
									ByAlert.alert("起租月应小于止租月");
									return;
								}
								if ((Integer.parseInt(startYears[2])
										- (Integer.parseInt(endYears[2])) > 0)) {
									ByAlert.alert("起租日应小于止租日");
									return;
								}
								if ((Integer.parseInt(startYears[0])
										- (Integer.parseInt(endYears[0])) == 0)) {
									qishu = 12;
								} else {
									qishu = selectEndYear - selectStartYear;
								}
								selectEndYear = Integer.parseInt(endYears[0]);
								selectStartYear = Integer
										.parseInt(startYears[0]);

								Intent intent = new Intent(
										ActivityEditHeTongFangdong.this,
										ActivityEditFangZuXinXi.class);
								intent.putExtra("yajin", yajin);
								intent.putExtra("qishu", qishu);
								startActivityForResult(intent, 105);
							}
							if ((v.getTag() + "").equals("deposit")) {

							}
							if ((v.getTag() + "").equals("start_date")) {
								Calendar c = Calendar.getInstance();
								new DoubleDatePickerDialog(
										ActivityEditHeTongFangdong.this,
										0,
										new DoubleDatePickerDialog.OnDateSetListener() {

											@Override
											public void onDateSet(
													DatePicker startDatePicker,
													int startYear,
													int startMonthOfYear,
													int startDayOfMonth) {
												selectStartYear = startYear;
												selectStartMonth = startMonthOfYear;
												String textString = String
														.format("%d-%d-%d",
																startYear,
																startMonthOfYear + 1,
																startDayOfMonth);
												((EditText) view
														.findViewById(R.id.edit))
														.setText(textString);
												((EditText) view
														.findViewById(R.id.edit))
														.setVisibility(View.VISIBLE);
											}
										}, c.get(Calendar.YEAR), c
												.get(Calendar.MONTH), c
												.get(Calendar.DATE), false)
										.show();
							}
							if ((v.getTag() + "").equals("end_date")) {
								Calendar c = Calendar.getInstance();
								new DoubleDatePickerDialog(
										ActivityEditHeTongFangdong.this,
										0,
										new DoubleDatePickerDialog.OnDateSetListener() {

											@Override
											public void onDateSet(
													DatePicker startDatePicker,
													int startYear,
													int startMonthOfYear,
													int startDayOfMonth) {
												selectEndYear = startYear;
												selectEndMonth = startMonthOfYear;
												String textString = String
														.format("%d-%d-%d",
																startYear,
																startMonthOfYear + 1,
																startDayOfMonth);
												((EditText) view
														.findViewById(R.id.edit))
														.setText(textString);
												((EditText) view
														.findViewById(R.id.edit))
														.setVisibility(View.VISIBLE);
											}
										}, c.get(Calendar.YEAR), c
												.get(Calendar.MONTH), c
												.get(Calendar.DATE), false)
										.show();
							}
						}
					});
				}
				tijiao.setVisibility(View.VISIBLE);
			} else if (entity.getEventType() == UserPresenter.heTongParams_fail) {
				ByAlert.alert(entity.getData());
			} else if (entity.getEventType() == UserPresenter.heTongTiJiao_success) {
				Intent intent=new Intent();
				intent.putExtra("shenfen", "lesser");
				intent.putExtra("contractNo", contractNo);
				sendBroadcast(intent);
				ByAlert.alert(entity.getData());
				finish();
			} else if (entity.getEventType() == UserPresenter.heTongTiJiao_fail) {
				ByAlert.alert(entity.getData());
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 101 && resultCode == 102) {
			if (data != null) {
				selectDevice = data.getStringExtra("selectDevice");
				for (View v : views) {
					if (v.getTag().toString().equals("facility")) {
						v.findViewById(R.id.txt_device).setVisibility(
								View.VISIBLE);
						((TextView) v.findViewById(R.id.txt_device))
								.setText(selectDevice);
					}
				}
			}
		}
		if (requestCode == 103 && resultCode == 104) {
			selectFeiYong = data.getStringExtra("select");
			unselectFeiYong = data.getStringExtra("unselect");
			for (View v : views) {
				if (v.getTag().toString().equals("renter_fee_items")) {
					v.findViewById(R.id.txt_device).setVisibility(View.VISIBLE);
					((TextView) v.findViewById(R.id.txt_device))
							.setText(selectFeiYong);
				}
				if (v.getTag().toString().equals("lessor_fee_items")) {
					v.findViewById(R.id.txt_device).setVisibility(View.VISIBLE);
					((TextView) v.findViewById(R.id.txt_device))
							.setText(unselectFeiYong);
				}
			}
		}
		if (requestCode == 105 && resultCode == 106) {
			zujinxinxi = data.getStringExtra("zujinxinxi");
			for (View v : views) {
				if (v.getTag().toString().equals("rent_info")) {
					v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
					((EditText) v.findViewById(R.id.edit)).setText("已填写");
				}
			}
		}
		if (requestCode == 107 && resultCode == 108) {// 上传签字图片
			imgId = data.getStringExtra("imgId");
			for (View v : views) {
				if (v.getTag().toString().equals("sign_leaser")) {
					v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
					((EditText) v.findViewById(R.id.edit)).setText("已签名");
				}
			}
		}

	}

}
